/*
    包含 n 个接口请求函数的模块
    每个函数返回 promise
*/
import jsonp from "jsonp";
import ajax from "./ajax";
import { message } from "antd";

// 登陆
export const reqLogin = (username, password) => ajax("/login", { username, password }, "POST");

// 6 获取一级或二级分类列表
export const reqCategorys = (parentId) => ajax("/manage/category/list", {parentId}, "GET");

// 7 添加分类
export const reqAddCategory = (parentId, categoryName) => ajax("/manage/category/add", {parentId, categoryName}, "POST");

// 8 更新新品类名词
export const reqUpdateCategory = (categoryId, categoryName) => ajax("/manage/category/update", {categoryId, categoryName}, "POST");


// 10. 获取商品分页列表
export const reqProducts = (pageNum, pageSize) => ajax("/manage/product/list", {pageNum, pageSize}, "GET");

// 11 根据ID/Name搜索产品分页列表 (一箭双雕，两个请求)
export const reqSearchProducts = ({pageNum, pageSize, searchType, searchName}) =>
  ajax('/manage/product/search', {
  pageNum,
  pageSize,
  [searchType]: searchName,
})

// product-detail 获取一个分类
export const reqCategory = (categoryId) => ajax('/manage/category/info', {categoryId});

// 更新商品的状态（上架/下架）
export const reqUpdateProductStatus = (productId, status) =>
  ajax('/manage/product/updateStatus', {
    productId,
    status
}, 'POST')

// 删除图片
export const reqDeleteImg = (name) => ajax('/manage/img/delete', {name}, 'post');

// 添加 / 更新商品
export const reqAddOrUpdateProduct = (product) => ajax('/manage/product/' +
(product._id ? 'update' : 'add'), product, 'post')

// 获取所有角色的列表
export const reqRoles = () => ajax('/manage/role/list')
// 添加角色
export const reqAddRole = (roleName) => ajax('/manage/role/add', {roleName}, 'POST');
// 更新角色权限
export const reqUpdateRole = (role) => ajax('/manage/role/update', role , 'POST');

// 获取所有用户的列表
export const reqUsers = () => ajax('/manage/user/list')

// 删除指定用户
export const reqDeleteUser = (userId) => ajax('/manage/user/delete', {userId}, 'POST');

// 添加/更新用户
export const reqAddOrUpdateUser = (user) => ajax('/manage/user/'+(user._id ? 'update' : 'add'), user, 'POST')

/*
通过 jsonp 请求获取天气信息
*/
export const reqWeather = (city) => {

  return new Promise((resolve, reject) => {
    const url = `http://api.map.baidu.com/telematics/v3/weather?location=${city}&output=json&ak=3p49MVra6urFRGOT9s8UBWr2`;
    jsonp(url, {},
      (err, data) => {
        // console.log('jsonp()', err, data);
        if (!err && data.status === 'success') { // 请求成功
          // 取出需要的数据
          const { dayPictureUrl, weather } = data.results[0].weather_data[0];
          resolve({ dayPictureUrl, weather });
        } else {
          message.err(" 获取天气信息失败");
        }  
    });
  });
}
